package com.myapp.ruyixing.ui;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;

import com.myapp.ruyixing.R;
import com.myapp.ruyixing.ui.widget.DatePickerFragment;
import com.myapp.ruyixing.utils.TimeUtils;

public class TrainTicketSearchFragment extends Fragment implements
		OnClickListener, OnDateSetListener {

	private Button mFromCityView;
	private Button mToCityView;
	private View mSwapView;
	private Button mStartDayView;
	private Spinner mClassView;
	private Spinner mTrainView;

	private int mPickField;
	private Calendar mPickDateCalendar;

	private static final int PICK_FIELD_START = 1;
	private static final int PICK_FIELD_END = 2;

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();

		mFromCityView = null;
		mToCityView = null;
		mSwapView = null;
		mStartDayView = null;
		mClassView = null;
		mTrainView = null;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.activity_train_ticket_search,
				container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		mFromCityView = (Button) view.findViewById(R.id.from_city);
		mToCityView = (Button) view.findViewById(R.id.to_city);
		mStartDayView = (Button) view.findViewById(R.id.cal_start);
		mClassView = (Spinner) view.findViewById(R.id.choose_class);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				getActivity(), R.array.train_ticket_class_array,
				R.layout.cell_air_ticket_class);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mClassView.setAdapter(adapter);
		mSwapView = view.findViewById(R.id.swap);
		mTrainView = (Spinner) view.findViewById(R.id.choose_train);
		ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
				getActivity(), R.array.train_category_array,
				R.layout.cell_air_ticket_class);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mTrainView.setAdapter(adapter2);

		mFromCityView.setOnClickListener(this);
		mToCityView.setOnClickListener(this);
		mStartDayView.setOnClickListener(this);
		mSwapView.setOnClickListener(this);

		mPickDateCalendar = Calendar.getInstance();
		mPickDateCalendar.add(Calendar.DAY_OF_YEAR, 1);
		mStartDayView.setText(TimeUtils.getDayString(mPickDateCalendar));

		view.findViewById(R.id.search).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cal_start:
			pickDate(TimeUtils.parsrDate(mStartDayView.getText().toString()));
			mPickField = PICK_FIELD_START;
			break;
		case R.id.cal_end:
			pickDate(TimeUtils.parsrDate(mStartDayView.getText().toString()));
			mPickField = PICK_FIELD_END;
			break;
		case R.id.swap:
			CharSequence fromCity = mFromCityView.getText();
			mFromCityView.setText(mToCityView.getText());
			mToCityView.setText(fromCity);
			break;
		case R.id.search:
			startSearch();
			break;
		case R.id.from_city:
			startActivityForResult(new Intent(getActivity(),
					CityListActivity.class).putExtra("train_city", true), 0);
			break;
		case R.id.to_city:
			startActivityForResult(new Intent(getActivity(),
					CityListActivity.class).putExtra("train_city", true), 1);
			break;

		default:
			break;
		}
	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		mPickDateCalendar = TimeUtils
				.getCalendar(year, monthOfYear, dayOfMonth);
		CharSequence dateString = TimeUtils.getDayString(mPickDateCalendar);
		if (mPickField == PICK_FIELD_START) {
			mStartDayView.setText(dateString);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK && data != null) {
			if (requestCode == 0) {
				mFromCityView.setText(data.getStringExtra("cityname"));
			} else if (requestCode == 1) {
				mToCityView.setText(data.getStringExtra("cityname"));
				
			}
		}
	}

	private void pickDate(Calendar c) {
		FragmentTransaction ft = getChildFragmentManager().beginTransaction();
		Fragment prev = getChildFragmentManager().findFragmentByTag(
				"datepicker");
		if (prev != null) {
			return;
		}
		ft.addToBackStack(null);

		// Create and show the dialog.
		DialogFragment newFragment = DatePickerFragment
				.getDatePickerFragment(c);

		newFragment.show(ft, "datepicker");
	}

	private void startSearch() {
		String from = mFromCityView.getText().toString();
		String to = mToCityView.getText().toString();
		String date = null;
		if (mPickDateCalendar != null) {
			date = TimeUtils.getString(mPickDateCalendar, "yyyy-MM-dd")
					.toString();
		}
		int traintype = mTrainView.getSelectedItemPosition();
		int tickettype = mClassView.getSelectedItemPosition();

		startActivityForResult(
				new Intent(getActivity(), TrainTicketSearchResultActivity.class)
						.putExtra("from", from).putExtra("to", to)
						.putExtra("date", date)
						.putExtra("traintype", traintype)
						.putExtra("tickettype", tickettype), 0);
	}
}
